<?php
/**
 * 采用swoole构建的TCP通信封装库
 * User: lang@vip.deyi.com
 * Date: 2017/6/22
 * Time: 12:35
 */

namespace Deyi\Functions;

/**
 * Class SocketFunction
 * @package Deyi\Functions
 */
class SocketFunction
{
    /**
     * TCP同步请求(Msgpack封装)
     * @version APP6.3.0
     * @author lang@vip.deyi.com
     * @param $host
     * @param $port
     * @param $data
     * @param float $timeout
     * @return bool
     */
    public static function syncTcpRequeset($host, $port, $data, $timeout = 0.5)
    {

        $client = new \swoole_client(SWOOLE_TCP);
        $data = msgpack_pack($data);
        $sendMsg = pack("N", strlen($data)) . $data;
        if (!@$client->connect($host, $port, $timeout) || !@$client->send($sendMsg)) {
            return false;
        }

        if ($ret = $client->recv()) {
            $ret = msgpack_unpack($ret);
        }
        $client->close();
        return $ret;
    }
}